package core

import (
	"context"
	"encoding/json"
	"ez/apps/core/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type RequestLog struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64            `json:"id" bson:"id,omitempty"`
	Url         string           `json:"url" bson:"url"`         //
	Session     string           `json:"session" bson:"session"` //
	Logs        []*ez.SessionLog `json:"logs" bson:"logs"`       //
	CreateAt    time.Time        `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time        `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time       `json:"deleteAt" bson:"deleteAt"`
}

func (this *RequestLog) DocName() string { return "RequestLog" }
func (this *RequestLog) GetId() int64    { return this.Id }
func (this *RequestLog) SetId(id int64)  { this.Id = id }
func (this *RequestLog) Create() error {
	return this.GetFactory().Create(this)
}
func (this *RequestLog) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *RequestLog) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *RequestLog) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *RequestLog) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *RequestLog) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *RequestLog) ToString() string {
	return string(this.ToBytes())
}
func (this *RequestLog) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *RequestLog) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *RequestLog) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *RequestLog) ClearRelationsBeforeSave() mgo.Doc {
	return this
}
func neverUsed_RequestLog() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type RequestLogAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *RequestLog
	Session *ez.Session
}

func NewRequestLogAccessControl(model *RequestLog, action string, session *ez.Session) *RequestLogAccessControl {
	ctrl := &RequestLogAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.RequestLogAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
